# -*- coding: utf-8 -*-

from core.serializers import CustomModelSerializer
from rest_framework import serializers
from apps.oms.models import Hawkeye, HawkeyeJob, HawkeyeJobPlugin
from core.relations import BaseNameWritableRelatedField


class HawkeyeSerializer(CustomModelSerializer):
    """
    鹰眼监控-序列化器
    """

    host = serializers.SlugRelatedField(
        many=False, read_only=True, slug_field="address"
    )

    class Meta:
        model = Hawkeye
        fields = "__all__"
        read_only_fields = ["id"]


class HawkeyeJobListSerializer(CustomModelSerializer):
    """
    鹰眼监控任务列表-序列化器
    """

    class Meta:
        model = HawkeyeJob
        fields = "__all__"
        read_only_fields = ["id"]


class HawkeyeJobSerializer(CustomModelSerializer):
    """
    鹰眼监控任务详情-序列化器
    """

    plugin = BaseNameWritableRelatedField(
        required=False, allow_empty=True, allow_null=True
    )
    hosts = BaseNameWritableRelatedField(many=True)

    class Meta:
        model = HawkeyeJob
        fields = "__all__"
        read_only_fields = ["id"]


class HawkeyeJobPluginSerializer(CustomModelSerializer):
    """
    鹰眼监控任务插件-序列化器
    """

    file = serializers.SerializerMethodField(read_only=True)

    def get_file(self, instance):
        return "/media/" + str(instance.file)

    class Meta:
        model = HawkeyeJobPlugin
        fields = "__all__"

    def create(self, validated_data):
        validated_data["name"] = str(self.initial_data.get("file"))
        validated_data["file"] = self.initial_data.get("file")
        validated_data["size"] = self.initial_data.get("file").size
        return super().create(validated_data)
